package com.carmaintain.servlets;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;

import com.carmaintain.common.Utils;
import com.carmaintain.config.Configs;

/**
 * Servlet implementation class Test
 */
public class Test extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Test() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String method = request.getParameter("method_name");
		String param = "";
		List<String> keys = Utils.sortKeys(request.getParameterNames());
		for (String key : keys) {
			if ("method_name".equals(key)) {continue;}
			if ("POST".equalsIgnoreCase(request.getMethod())) {
				param += "".equals(param) ? key + "=" + URLEncoder.encode(new String(request.getParameter(key).getBytes("ISO-8859-1"), "UTF-8"), "UTF-8") : "&" + key + "=" + URLEncoder.encode(new String(request.getParameter(key).getBytes("ISO-8859-1"), "UTF-8"), "UTF-8");
			} else {
				param += "".equals(param) ? key + "=" + URLEncoder.encode(request.getParameter(key), "UTF-8") : "&" + key + "=" + URLEncoder.encode(request.getParameter(key), "UTF-8");
			}
		}
		try {
			param += "&sign=" + Utils.md5(param + Configs.PUBLIC_KEY);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		String result = "";
		if ("POST".equalsIgnoreCase(request.getMethod())) {
			URL url = new URL(request.getScheme() + "://" + request.getServerName() + ":" 
					+ request.getServerPort() + request.getContextPath() + "/" + method);
			URLConnection conn = url.openConnection();
			conn.setDoOutput(true);
			OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
			out.write(URLDecoder.decode(param, "UTF-8"));
			out.flush();
			out.close();

			BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			String res = br.readLine();
			while (res != null) {
				result += res;
				res = br.readLine();
			}
		} else {
			URL url = new URL(request.getScheme() + "://" + request.getServerName() + ":" 
					+ request.getServerPort() + request.getContextPath() + "/" + method + "?" + param);
			URLConnection conn = url.openConnection();
			conn.connect();
			BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			String res = br.readLine();
			while (res != null) {
				result += res;
				res = br.readLine();
			}
		}
		
		Object userid = "";
		Object usercode = "";
		if ("merchant/login".equals(method)) {
			try {
				userid = JSONObject.fromObject(result).getJSONObject("resultData").get("userid");
				usercode = JSONObject.fromObject(JSONObject.fromObject(result).getJSONObject("resultData")).get("usercode");
			} catch (Exception e) {
			}
			request.getSession().setAttribute("merchant_id", userid);
			request.getSession().setAttribute("usercode", usercode);
		}
		
		if ("customer/login".equals(method)) {
			try {
				userid = JSONObject.fromObject(result).getJSONObject("resultData").get("userid");
				usercode = JSONObject.fromObject(JSONObject.fromObject(result).getJSONObject("resultData")).get("usercode");
			} catch (Exception e) {
			}
			request.getSession().setAttribute("customer_id", userid);
			request.getSession().setAttribute("usercode", usercode);
		}
		

		result = result.replaceAll(",", ", ");
		result = result.replaceAll("\\{", "{ ");
		result = result.replaceAll("\\}", "} ");
		result = formatString(result.trim());
		
		result = "<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'></head>" 
				+ "<br/>"
				+ request.getScheme() + "://" + request.getServerName() + ":" 
				+ request.getServerPort() + request.getContextPath() + "/" + method + "?" + param
				+ "<br/>"
				+ "<input id='merchant_id' type='hidden' value='" + request.getSession().getAttribute("merchant_id") + "'/>"
				+ "<input id='customer_id' type='hidden' value='" + request.getSession().getAttribute("customer_id") + "'/>"
				+ "<input id='usercode' type='hidden' value='" + request.getSession().getAttribute("usercode") + "'/>"
				+ result
				+ "</html>";
		
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(result);
	}
	
	private String formatString(String result) {
		String ret = "";
		int level = 0;
		String[] tmps = result.split("\\{");
		for (int i = 0; i < tmps.length; i++) {
			if (tmps[i] == null || "".equals(tmps[i].trim())) {continue;}
			ret += "<br/>" + genSpaces(level++) + "{<br/>" + genSpaces(level);
			String[] tmps2 = tmps[i].split("\\}");
			for (int j = 0; j < tmps2.length; j++) {
				ret += tmps2[j].replaceAll(",", "," + "<br/>" + genSpaces(level));
				if (j < tmps2.length - 1) {
					ret += "<br/>" + genSpaces(--level) + "}";
				}
			}
			if (tmps[i].lastIndexOf("}") == tmps[i].length() - 1) {
				ret += "<br/>" + genSpaces(--level) + "}";
			}
		}
		
		if (tmps.length == 1) {
			return result; 
		}
		
		return ret;
	}
	
	private String genSpaces(int level) {
		String spaces = "";
		while(level > 0) {
			spaces += "&nbsp;&nbsp;&nbsp;&nbsp;";
			level--;
		}
		return spaces;
	} 

}
